package com.bawei.image

import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import java.io.ByteArrayOutputStream

/**
 * Bitmap图片处理工具
 */
object BitmapUtil {

    /**
     * 方式一：质量压缩
     */
    fun compressQuality(res: Resources, resId: Int, quality: Int): Bitmap{
        var bm = BitmapFactory.decodeResource(res, resId)
        var bos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos)
        bm.recycle()
        var bytes = bos.toByteArray()
        return BitmapFactory.decodeByteArray(bytes, quality, bytes.size)
    }

    /**
     * 方式二：缩放压缩
     */
    fun compressScale(res: Resources, resId: Int, targetWidth: Int, targetHeight: Int): Bitmap{
        var bm = BitmapFactory.decodeResource(res, resId)
        return Bitmap.createScaledBitmap(bm, targetWidth, targetHeight, true)
    }

    /**
     * 方式三：矩阵压缩
     */
    fun compressMatrix(res: Resources, resId: Int, sx: Float, sy: Float): Bitmap{
        var matrix = Matrix()
        matrix.setScale(sx, sy)
        var bm = BitmapFactory.decodeResource(res, resId)
        return Bitmap.createBitmap(bm, 0, 0, bm.width, bm.height, matrix, true)
    }

    /**
     * 方式四：使用编码格式：RGB_565，RGB265，ARGB_8888, RGB_444等
     * A: 代表透明度，R：代表红色， G: 代表绿色， B: 代表蓝色
     */
    fun compressRgb(res: Resources, resId: Int): Bitmap{
        var options = BitmapFactory.Options()
        options.inPreferredConfig = Bitmap.Config.RGB_565
        return BitmapFactory.decodeResource(res, resId, options)
    }

    /**
     * 方式四：二次采样压缩（推荐）
     */
    fun compressSecondSample(res: Resources, resId: Int, maxWidth: Int, maxHeight: Int): Bitmap{
        //第一步加载图片，只读取图标宽和高，不加载像素值
        var options = BitmapFactory.Options()
        options.inJustDecodeBounds = true //确保只加载图片的宽和高
        BitmapFactory.decodeResource(res, resId, options)
        //获取图片宽和高
        var originWidth = options.outWidth
        var originHeight = options.outHeight

        //第二次计算采样率
        var sampleSize = 1
        while (originWidth > maxWidth || originHeight > maxHeight){
            sampleSize *= 2 //每循环一次就减少一半
            originWidth /= sampleSize
            originHeight /= sampleSize
        }

        options.inJustDecodeBounds = false //关闭掉，加载图片加载像素值
        options.inSampleSize = sampleSize //设置采样率大小
        options.inPreferredConfig = Bitmap.Config.RGB_565 //设置图片编码格式

        return BitmapFactory.decodeResource(res, resId, options)
    }

}